#!/usr/bin/env python3
"""
S3 Bucket Location Tool - GetBucketLocation API 演示工具

这个工具演示如何使用 GetBucketLocation API 获取桶的区域信息。

使用示例:
    python s3_bucket_location.py --name my-bucket
    python s3_bucket_location.py --all-buckets
    python s3_bucket_location.py --stats
    python s3_bucket_location.py --format json
    python s3_bucket_location.py --verbose
"""

import argparse
import boto3
import json
import sys
from collections import Counter
from datetime import datetime, timezone
from botocore.config import Config
from botocore.exceptions import ClientError, NoCredentialsError


class BucketLocationClient:
    """S3 桶位置查询客户端"""
    
    def __init__(self, endpoint_url='http://localhost:8000', 
                 access_key='AKIAIOSFODNN7EXAMPLE', 
                 secret_key='wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
                 region='us-east-1'):
        """
        初始化桶位置查询客户端
        
        Args:
            endpoint_url: S3 服务端点
            access_key: AWS Access Key
            secret_key: AWS Secret Key
            region: AWS 区域
        """
        self.endpoint_url = endpoint_url
        self.access_key = access_key
        self.secret_key = secret_key
        self.region = region
        self._client = None
    
    def _get_client(self):
        """获取 S3 客户端"""
        if self._client is None:
            self._client = boto3.client(
                's3',
                endpoint_url=self.endpoint_url,
                aws_access_key_id=self.access_key,
                aws_secret_access_key=self.secret_key,
                region_name=self.region,
                config=Config(s3={'addressing_style': 'path'})
            )
        return self._client


    def get_single_bucket_location(self, bucket_name):
        """简单格式获取单个桶的位置信息"""
        try:
            s3_client = self._get_client()
            response = s3_client.get_bucket_location(Bucket=bucket_name)
            
            # AWS 的特殊处理：us-east-1 返回 None 或空字符串
            location = response.get('LocationConstraint')
            if not location:
                location = 'us-east-1'
            
            print(f"🌐 桶位置信息: {bucket_name}")
            print(f"   📍 区域: {location}")
            
            # 显示区域的详细信息
            region_info = self._get_region_info(location)
            if region_info:
                print(f"   🏛️  区域名称: {region_info['name']}")
                print(f"   🌍 地理位置: {region_info['location']}")
            
            return location
            
        except ClientError as e:
            error_code = e.response['Error']['Code']
            error_msg = e.response['Error']['Message']
            
            if error_code == 'NoSuchBucket':
                print(f"❌ 桶不存在: {bucket_name}")
            else:
                print(f"❌ 获取位置失败 [{error_code}]: {error_msg}")
            
            return None
        except NoCredentialsError:
            print("❌ 错误: 未找到 AWS 凭据")
            return None
        except Exception as e:
            print(f"❌ 未知错误: {e}")
            return None
    
    def get_single_bucket_location_verbose(self, bucket_name):
        """详细格式获取单个桶的位置信息"""
        try:
            s3_client = self._get_client()
            print("🌐 桶位置查询详细信息:")
            print("=" * 50)
            print(f"   🗂️  桶名称: {bucket_name}")
            print(f"   🌐 区域: {self.region}")
            print(f"   🔗 服务端点: {self.endpoint_url}")
            print(f"   📅 查询时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
            print()
            
            response = s3_client.get_bucket_location(Bucket=bucket_name)
            
            # AWS 的特殊处理：us-east-1 返回 None 或空字符串
            location = response.get('LocationConstraint')
            if not location:
                location = 'us-east-1'
            
            print(f"   ✅ 位置查询成功")
            print(f"   📍 区域代码: {location}")
            
            # 显示区域的详细信息
            region_info = self._get_region_info(location)
            if region_info:
                print(f"   🏛️  区域名称: {region_info['name']}")
                print(f"   🌍 地理位置: {region_info['location']}")
            
            print(f"   📊 查询完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
            
            return location
            
        except ClientError as e:
            error_code = e.response['Error']['Code']
            error_msg = e.response['Error']['Message']
            
            print(f"   ❌ 查询失败:")
            print(f"      错误代码: {error_code}")
            print(f"      错误信息: {error_msg}")
            
            if error_code == 'NoSuchBucket':
                print(f"   📋 状态: 桶不存在")
            else:
                print(f"   📋 状态: 查询失败")
            
            return None
        except NoCredentialsError:
            print("   ❌ 错误: 未找到 AWS 凭据")
            return None
        except Exception as e:
            print(f"   ❌ 未知错误: {e}")
            return None
    
    def get_single_bucket_location_json(self, bucket_name):
        """JSON 格式获取单个桶的位置信息"""
        try:
            s3_client = self._get_client()
            response = s3_client.get_bucket_location(Bucket=bucket_name)
            
            # AWS 的特殊处理：us-east-1 返回 None 或空字符串
            location = response.get('LocationConstraint')
            if not location:
                location = 'us-east-1'
            
            # 获取区域详细信息
            region_info = self._get_region_info(location)
            
            result = {
                "success": True,
                "bucket_name": bucket_name,
                "location_constraint": location,
                "region_info": region_info,
                "query_time": datetime.now().isoformat()
            }
            
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return location
            
        except ClientError as e:
            error_code = e.response['Error']['Code']
            error_msg = e.response['Error']['Message']
            
            if error_code == 'NoSuchBucket':
                result = {
                    "success": False,
                    "bucket_name": bucket_name,
                    "error": "NoSuchBucket",
                    "error_message": "桶不存在",
                    "query_time": datetime.now().isoformat()
                }
            else:
                result = {
                    "success": False,
                    "bucket_name": bucket_name,
                    "error": error_code,
                    "error_message": error_msg,
                    "query_time": datetime.now().isoformat()
                }
            
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return None
        except NoCredentialsError:
            result = {
                "success": False,
                "error": "NoCredentials",
                "error_message": "未找到 AWS 凭据",
                "query_time": datetime.now().isoformat()
            }
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return None
        except Exception as e:
            result = {
                "success": False,
                "error": "Unknown",
                "error_message": str(e),
                "query_time": datetime.now().isoformat()
            }
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return None


    def get_all_bucket_locations(self):
        """简单格式获取所有桶的位置信息"""
        try:
            s3_client = self._get_client()
            # 列出所有桶
            response = s3_client.list_buckets()
            buckets = response['Buckets']
            
            if not buckets:
                print("📭 账户下没有桶")
                return {}
            
            print(f"🌐 获取 {len(buckets)} 个桶的位置信息:")
            print("=" * 60)
            
            bucket_locations = {}
            
            for bucket in buckets:
                bucket_name = bucket['Name']
                created = bucket['CreationDate'].strftime('%Y-%m-%d %H:%M:%S')
                
                print(f"\n📦 桶: {bucket_name}")
                print(f"   📅 创建时间: {created}")
                
                location = self.get_single_bucket_location_simple(bucket_name)
                if location:
                    bucket_locations[bucket_name] = location
                
            return bucket_locations
            
        except ClientError as e:
            error_code = e.response['Error']['Code']
            error_msg = e.response['Error']['Message']
            print(f"❌ S3 错误 [{error_code}]: {error_msg}")
            return {}
        except NoCredentialsError:
            print("❌ 错误: 未找到 AWS 凭据")
            return {}
        except Exception as e:
            print(f"❌ 获取桶列表失败: {e}")
            return {}
    
    def get_all_bucket_locations_verbose(self):
        """详细格式获取所有桶的位置信息"""
        try:
            s3_client = self._get_client()
            print("🌐 批量桶位置查询详细信息:")
            print("=" * 60)
            print(f"   🌐 区域: {self.region}")
            print(f"   🔗 服务端点: {self.endpoint_url}")
            print(f"   📅 开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
            print()
            
            # 列出所有桶
            response = s3_client.list_buckets()
            buckets = response['Buckets']
            
            if not buckets:
                print("   📭 账户下没有桶")
                return {}
            
            print(f"   📚 发现 {len(buckets)} 个桶，开始位置查询:")
            print("   " + "=" * 60)
            
            bucket_locations = {}
            
            for i, bucket in enumerate(buckets, 1):
                bucket_name = bucket['Name']
                created = bucket['CreationDate'].strftime('%Y-%m-%d %H:%M:%S')
                
                print(f"   [{i}/{len(buckets)}] 查询桶: {bucket_name}")
                print(f"       📅 创建时间: {created}")
                
                location = self.get_single_bucket_location_verbose(bucket_name)
                if location:
                    bucket_locations[bucket_name] = location
                    print(f"   ✅ 成功")
                else:
                    print(f"   ❌ 失败")
                print()
            
            print(f"   📊 查询统计:")
            print(f"      • 总桶数: {len(buckets)}")
            print(f"      • 成功查询: {len(bucket_locations)}")
            print(f"      • 失败查询: {len(buckets) - len(bucket_locations)}")
            print(f"      • 成功率: {(len(bucket_locations)/len(buckets))*100:.1f}%")
            print(f"   📅 完成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
            
            return bucket_locations
            
        except Exception as e:
            print(f"   ❌ 批量查询失败: {e}")
            return {}
    
    def get_all_bucket_locations_json(self):
        """JSON 格式获取所有桶的位置信息"""
        try:
            s3_client = self._get_client()
            
            # 列出所有桶
            response = s3_client.list_buckets()
            buckets = response['Buckets']
            
            if not buckets:
                result = {
                    "success": True,
                    "operation": "get_all_bucket_locations",
                    "total_buckets": 0,
                    "bucket_locations": {},
                    "message": "账户下没有桶",
                    "query_time": datetime.now().isoformat()
                }
                print(json.dumps(result, indent=2, ensure_ascii=False))
                return {}
            
            bucket_locations = {}
            bucket_results = []
            
            for bucket in buckets:
                bucket_name = bucket['Name']
                created = bucket['CreationDate']
                
                try:
                    location_response = s3_client.get_bucket_location(Bucket=bucket_name)
                    location = location_response.get('LocationConstraint')
                    if not location:
                        location = 'us-east-1'
                    
                    region_info = self._get_region_info(location)
                    
                    bucket_result = {
                        "bucket_name": bucket_name,
                        "creation_date": created.isoformat(),
                        "location_constraint": location,
                        "region_info": region_info,
                        "success": True
                    }
                    
                    bucket_locations[bucket_name] = location
                    
                except ClientError as e:
                    error_code = e.response['Error']['Code']
                    error_msg = e.response['Error']['Message']
                    
                    bucket_result = {
                        "bucket_name": bucket_name,
                        "creation_date": created.isoformat(),
                        "success": False,
                        "error": error_code,
                        "error_message": error_msg
                    }
                except Exception as e:
                    bucket_result = {
                        "bucket_name": bucket_name,
                        "creation_date": created.isoformat(),
                        "success": False,
                        "error": "Unknown",
                        "error_message": str(e)
                    }
                
                bucket_results.append(bucket_result)
            
            # 输出汇总结果
            success_count = len(bucket_locations)
            result = {
                "success": success_count == len(buckets),
                "operation": "get_all_bucket_locations",
                "total_buckets": len(buckets),
                "successful_queries": success_count,
                "failed_queries": len(buckets) - success_count,
                "success_rate": f"{(success_count/len(buckets))*100:.1f}%",
                "bucket_locations": bucket_locations,
                "detailed_results": bucket_results,
                "query_time": datetime.now().isoformat()
            }
            
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return bucket_locations
            
        except ClientError as e:
            error_code = e.response['Error']['Code']
            error_msg = e.response['Error']['Message']
            error_result = {
                "success": False,
                "error": error_code,
                "error_message": error_msg,
                "query_time": datetime.now().isoformat()
            }
            print(json.dumps(error_result, indent=2, ensure_ascii=False))
            return {}
        except NoCredentialsError:
            error_result = {
                "success": False,
                "error": "NoCredentials",
                "error_message": "未找到 AWS 凭据",
                "query_time": datetime.now().isoformat()
            }
            print(json.dumps(error_result, indent=2, ensure_ascii=False))
            return {}
        except Exception as e:
            error_result = {
                "success": False,
                "error": "Unknown",
                "error_message": str(e),
                "query_time": datetime.now().isoformat()
            }
            print(json.dumps(error_result, indent=2, ensure_ascii=False))
            return {}


    def show_location_statistics(self, bucket_locations):
        """简单格式显示位置统计信息"""
        if not bucket_locations:
            print("📊 没有位置数据可统计")
            return
        
        print(f"\n📊 位置统计 (共 {len(bucket_locations)} 个桶):")
        print("=" * 50)
        
        # 统计各区域的桶数量
        location_counts = Counter(bucket_locations.values())
        
        # 按桶数量排序显示
        for location, count in location_counts.most_common():
            percentage = (count / len(bucket_locations)) * 100
            region_info = self._get_region_info(location)
            region_name = region_info['name'] if region_info else location
            
            print(f"🌍 {location:<15} {region_name:<25} {count:3d} 个桶 ({percentage:5.1f}%)")
        
        # 显示桶分布详情
        print(f"\n📋 桶分布详情:")
        print("-" * 50)
        
        for location in sorted(location_counts.keys()):
            buckets_in_location = [name for name, loc in bucket_locations.items() if loc == location]
            region_info = self._get_region_info(location)
            region_name = region_info['name'] if region_info else location
            
            print(f"\n🌍 {location} ({region_name}):")
            for bucket_name in sorted(buckets_in_location):
                print(f"   • {bucket_name}")
    
    def show_location_statistics_verbose(self, bucket_locations):
        """详细格式显示位置统计信息"""
        if not bucket_locations:
            print("   📊 没有位置数据可统计")
            return
        
        print(f"\n   📊 位置统计详细信息:")
        print("   " + "=" * 50)
        print(f"      • 总桶数: {len(bucket_locations)}")
        print(f"      • 统计时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print()
        
        # 统计各区域的桶数量
        location_counts = Counter(bucket_locations.values())
        
        print(f"   🌍 区域分布统计:")
        print("   " + "-" * 50)
        
        # 按桶数量排序显示
        for location, count in location_counts.most_common():
            percentage = (count / len(bucket_locations)) * 100
            region_info = self._get_region_info(location)
            region_name = region_info['name'] if region_info else location
            
            print(f"      {location:<15} {region_name:<25} {count:3d} 个桶 ({percentage:5.1f}%)")
        
        # 显示桶分布详情
        print(f"\n   📋 桶分布详情:")
        print("   " + "-" * 50)
        
        for location in sorted(location_counts.keys()):
            buckets_in_location = [name for name, loc in bucket_locations.items() if loc == location]
            region_info = self._get_region_info(location)
            region_name = region_info['name'] if region_info else location
            
            print(f"\n      🌍 {location} ({region_name}):")
            for bucket_name in sorted(buckets_in_location):
                print(f"         • {bucket_name}")
    
    def show_location_statistics_json(self, bucket_locations):
        """JSON 格式显示位置统计信息"""
        if not bucket_locations:
            result = {
                "success": True,
                "operation": "location_statistics",
                "total_buckets": 0,
                "message": "没有位置数据可统计",
                "statistics_time": datetime.now().isoformat()
            }
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return
        
        # 统计各区域的桶数量
        location_counts = Counter(bucket_locations.values())
        
        # 构建统计结果
        region_stats = []
        for location, count in location_counts.most_common():
            percentage = (count / len(bucket_locations)) * 100
            region_info = self._get_region_info(location)
            
            buckets_in_location = [name for name, loc in bucket_locations.items() if loc == location]
            
            region_stat = {
                "region_code": location,
                "region_name": region_info['name'] if region_info else location,
                "region_location": region_info['location'] if region_info else None,
                "bucket_count": count,
                "percentage": round(percentage, 1),
                "buckets": sorted(buckets_in_location)
            }
            region_stats.append(region_stat)
        
        result = {
            "success": True,
            "operation": "location_statistics",
            "total_buckets": len(bucket_locations),
            "total_regions": len(location_counts),
            "region_statistics": region_stats,
            "statistics_time": datetime.now().isoformat()
        }
        
        print(json.dumps(result, indent=2, ensure_ascii=False))
    
    def _get_region_info(self, region_code):
        """获取区域的详细信息"""
        regions = {
            'us-east-1': {'name': 'US East (N. Virginia)', 'location': '美国东部（弗吉尼亚北部）'},
            'us-east-2': {'name': 'US East (Ohio)', 'location': '美国东部（俄亥俄）'},
            'us-west-1': {'name': 'US West (N. California)', 'location': '美国西部（加利福尼亚北部）'},
            'us-west-2': {'name': 'US West (Oregon)', 'location': '美国西部（俄勒冈）'},
            'eu-west-1': {'name': 'Europe (Ireland)', 'location': '欧洲（爱尔兰）'},
            'eu-west-2': {'name': 'Europe (London)', 'location': '欧洲（伦敦）'},
            'eu-west-3': {'name': 'Europe (Paris)', 'location': '欧洲（巴黎）'},
            'eu-central-1': {'name': 'Europe (Frankfurt)', 'location': '欧洲（法兰克福）'},
            'ap-east-1': {'name': 'Asia Pacific (Hong Kong)', 'location': '亚太地区（香港）'},
            'ap-south-1': {'name': 'Asia Pacific (Mumbai)', 'location': '亚太地区（孟买）'},
            'ap-southeast-1': {'name': 'Asia Pacific (Singapore)', 'location': '亚太地区（新加坡）'},
            'ap-southeast-2': {'name': 'Asia Pacific (Sydney)', 'location': '亚太地区（悉尼）'},
            'ap-northeast-1': {'name': 'Asia Pacific (Tokyo)', 'location': '亚太地区（东京）'},
            'ap-northeast-2': {'name': 'Asia Pacific (Seoul)', 'location': '亚太地区（首尔）'},
            'cn-north-1': {'name': 'China (Beijing)', 'location': '中国（北京）'},
            'cn-northwest-1': {'name': 'China (Ningxia)', 'location': '中国（宁夏）'},
        }
        
        return regions.get(region_code)


    def check_compliance(self, bucket_locations, required_regions=None):
        """简单格式检查合规性"""
        if not bucket_locations:
            print("📊 没有数据可检查合规性")
            return
        
        print(f"\n🔍 合规性检查:")
        print("-" * 30)
        
        # 检查是否有桶在指定区域
        if required_regions:
            print(f"要求区域: {', '.join(required_regions)}")
            
            compliant_buckets = []
            non_compliant_buckets = []
            
            for bucket_name, location in bucket_locations.items():
                if location in required_regions:
                    compliant_buckets.append(bucket_name)
                else:
                    non_compliant_buckets.append((bucket_name, location))
            
            print(f"✅ 合规桶: {len(compliant_buckets)}/{len(bucket_locations)}")
            print(f"❌ 不合规桶: {len(non_compliant_buckets)}/{len(bucket_locations)}")
            
            if non_compliant_buckets:
                print(f"\n不合规桶详情:")
                for bucket_name, location in non_compliant_buckets:
                    print(f"   • {bucket_name} (位于 {location})")
        
        # 检查数据主权
        us_regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2']
        eu_regions = ['eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-central-1']
        ap_regions = ['ap-east-1', 'ap-south-1', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ap-northeast-2']
        cn_regions = ['cn-north-1', 'cn-northwest-1']
        
        region_groups = {
            '美国': us_regions,
            '欧洲': eu_regions,
            '亚太': ap_regions,
            '中国': cn_regions
        }
        
        print(f"\n🌍 数据主权分析:")
        for group_name, regions in region_groups.items():
            buckets_in_group = [name for name, loc in bucket_locations.items() if loc in regions]
            if buckets_in_group:
                print(f"   {group_name}: {len(buckets_in_group)} 个桶")
    
    def check_compliance_verbose(self, bucket_locations, required_regions=None):
        """详细格式检查合规性"""
        if not bucket_locations:
            print("   📊 没有数据可检查合规性")
            return
        
        print(f"\n   🔍 合规性检查详细信息:")
        print("   " + "=" * 50)
        print(f"      • 检查时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print(f"      • 总桶数: {len(bucket_locations)}")
        print()
        
        # 检查是否有桶在指定区域
        if required_regions:
            print(f"   📋 区域合规性检查:")
            print(f"      要求区域: {', '.join(required_regions)}")
            
            compliant_buckets = []
            non_compliant_buckets = []
            
            for bucket_name, location in bucket_locations.items():
                if location in required_regions:
                    compliant_buckets.append(bucket_name)
                else:
                    non_compliant_buckets.append((bucket_name, location))
            
            print(f"      ✅ 合规桶: {len(compliant_buckets)}/{len(bucket_locations)}")
            print(f"      ❌ 不合规桶: {len(non_compliant_buckets)}/{len(bucket_locations)}")
            
            if non_compliant_buckets:
                print(f"      📋 不合规桶详情:")
                for bucket_name, location in non_compliant_buckets:
                    print(f"         • {bucket_name} (位于 {location})")
        
        # 检查数据主权
        us_regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2']
        eu_regions = ['eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-central-1']
        ap_regions = ['ap-east-1', 'ap-south-1', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ap-northeast-2']
        cn_regions = ['cn-north-1', 'cn-northwest-1']
        
        region_groups = {
            '美国': us_regions,
            '欧洲': eu_regions,
            '亚太': ap_regions,
            '中国': cn_regions
        }
        
        print(f"\n   🌍 数据主权分析:")
        for group_name, regions in region_groups.items():
            buckets_in_group = [name for name, loc in bucket_locations.items() if loc in regions]
            if buckets_in_group:
                print(f"      {group_name}: {len(buckets_in_group)} 个桶")
    
    def check_compliance_json(self, bucket_locations, required_regions=None):
        """JSON 格式检查合规性"""
        if not bucket_locations:
            result = {
                "success": True,
                "operation": "compliance_check",
                "total_buckets": 0,
                "message": "没有数据可检查合规性",
                "check_time": datetime.now().isoformat()
            }
            print(json.dumps(result, indent=2, ensure_ascii=False))
            return
        
        # 检查是否有桶在指定区域
        compliance_result = {}
        if required_regions:
            compliant_buckets = []
            non_compliant_buckets = []
            
            for bucket_name, location in bucket_locations.items():
                if location in required_regions:
                    compliant_buckets.append(bucket_name)
                else:
                    non_compliant_buckets.append({"bucket_name": bucket_name, "location": location})
            
            compliance_result = {
                "required_regions": required_regions,
                "compliant_buckets": compliant_buckets,
                "non_compliant_buckets": non_compliant_buckets,
                "compliance_rate": f"{(len(compliant_buckets)/len(bucket_locations))*100:.1f}%"
            }
        
        # 检查数据主权
        us_regions = ['us-east-1', 'us-east-2', 'us-west-1', 'us-west-2']
        eu_regions = ['eu-west-1', 'eu-west-2', 'eu-west-3', 'eu-central-1']
        ap_regions = ['ap-east-1', 'ap-south-1', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'ap-northeast-2']
        cn_regions = ['cn-north-1', 'cn-northwest-1']
        
        region_groups = {
            '美国': us_regions,
            '欧洲': eu_regions,
            '亚太': ap_regions,
            '中国': cn_regions
        }
        
        sovereignty_analysis = {}
        for group_name, regions in region_groups.items():
            buckets_in_group = [name for name, loc in bucket_locations.items() if loc in regions]
            if buckets_in_group:
                sovereignty_analysis[group_name] = {
                    "bucket_count": len(buckets_in_group),
                    "buckets": buckets_in_group,
                    "regions": regions
                }
        
        result = {
            "success": True,
            "operation": "compliance_check",
            "total_buckets": len(bucket_locations),
            "compliance_check": compliance_result,
            "sovereignty_analysis": sovereignty_analysis,
            "check_time": datetime.now().isoformat()
        }
        
        print(json.dumps(result, indent=2, ensure_ascii=False))


def parse_args():
    """解析命令行参数"""
    parser = argparse.ArgumentParser(
        description='S3 GetBucketLocation API 演示工具',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
示例:
  %(prog)s --name my-bucket                 # 获取单个桶的位置
  %(prog)s --all-buckets                    # 获取所有桶的位置
  %(prog)s --stats                          # 显示位置统计
  %(prog)s --all-buckets --compliance us-east-1,us-west-2  # 合规性检查
  %(prog)s --format json                    # JSON 格式输出
  %(prog)s --verbose                        # 详细格式输出
  %(prog)s --access-key KEY --secret-key SECRET  # 指定凭据
        """
    )
    
    parser.add_argument(
        '--host',
        default='http://localhost:8000',
        help='S3 服务端点 (默认: http://localhost:8000)'
    )
    
    parser.add_argument(
        '--access-key',
        default='AKIAIOSFODNN7EXAMPLE',
        help='AWS Access Key (默认: 测试密钥)'
    )
    
    parser.add_argument(
        '--secret-key',
        default='wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY',
        help='AWS Secret Key (默认: 测试密钥)'
    )
    
    parser.add_argument(
        '--region',
        default='us-east-1',
        help='AWS 区域 (默认: us-east-1)'
    )
    
    parser.add_argument(
        '--format',
        choices=['simple', 'verbose', 'json'],
        default='simple',
        help='输出格式 (默认: simple)'
    )
    
    parser.add_argument(
        '--verbose',
        action='store_true',
        help='详细输出模式 (等同于 --format verbose)'
    )
    
    # 查询选项
    query_group = parser.add_mutually_exclusive_group()
    query_group.add_argument(
        '--name',
        help='要查询的桶名称'
    )
    
    query_group.add_argument(
        '--all-buckets',
        action='store_true',
        help='获取所有桶的位置信息'
    )
    
    parser.add_argument(
        '--stats',
        action='store_true',
        help='显示位置统计信息'
    )
    
    parser.add_argument(
        '--compliance',
        help='合规性检查：指定允许的区域（逗号分隔）'
    )
    
    return parser.parse_args()


def main():
    """主函数"""
    args = parse_args()
    
    # 如果指定了 --verbose，覆盖 format 设置
    if args.verbose:
        args.format = 'verbose'
    
    # 参数验证
    if not args.name and not args.all_buckets:
        print("❌ 错误: 必须指定 --name 或 --all-buckets")
        sys.exit(1)
    
    # 创建客户端
    client = BucketLocationClient(
        endpoint_url=args.host,
        access_key=args.access_key,
        secret_key=args.secret_key,
        region=args.region
    )
    
    success = True
    bucket_locations = {}
    
    # 根据格式执行相应操作
    if args.name:
        if args.format == 'simple':
            location = client.get_single_bucket_location_simple(args.name)
        elif args.format == 'verbose':
            location = client.get_single_bucket_location_verbose(args.name)
        elif args.format == 'json':
            location = client.get_single_bucket_location_json(args.name)
        
        success = location is not None
        if location:
            bucket_locations[args.name] = location
    elif args.all_buckets:
        if args.format == 'simple':
            bucket_locations = client.get_all_bucket_locations_simple()
        elif args.format == 'verbose':
            bucket_locations = client.get_all_bucket_locations_verbose()
        elif args.format == 'json':
            bucket_locations = client.get_all_bucket_locations_json()
        
        success = len(bucket_locations) > 0
    
    # 显示统计信息
    if args.stats and bucket_locations:
        if args.format == 'simple':
            client.show_location_statistics_simple(bucket_locations)
        elif args.format == 'verbose':
            client.show_location_statistics_verbose(bucket_locations)
        elif args.format == 'json':
            client.show_location_statistics_json(bucket_locations)
    
    # 合规性检查
    if args.compliance and bucket_locations:
        required_regions = [r.strip() for r in args.compliance.split(',')]
        if args.format == 'simple':
            client.check_compliance_simple(bucket_locations, required_regions)
        elif args.format == 'verbose':
            client.check_compliance_verbose(bucket_locations, required_regions)
        elif args.format == 'json':
            client.check_compliance_json(bucket_locations, required_regions)
    
    # 设置退出码
    sys.exit(0 if success else 1)


if __name__ == '__main__':
    main()
